import { BasicColumn } from '/@/components/Table';
import { FormSchema } from '/@/components/Table';
import { Tag, Switch, Image } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { h, reactive } from 'vue';
import { getModelAllListApi, MODEL_TYPE, statusSwitchApi } from '/@/api/config-center/model-design';
import type { Rule } from 'ant-design-vue/es/form';
import { getDictTypeListApi } from '/@/api/admin/dict';
import { getTemplateDefinePageApi } from '/@/api/flow/flow';
import { DICT } from '/@/enums/dict';
import { useDebounceFn } from '@vueuse/core';
import { verify } from '/@/utils/validator';

const checkWord = async (_rule: Rule, value: string) => {
  if (!verify.upperAndLowerNum.value.test(value)) {
    return Promise.reject(verify.upperAndLowerNum.label);
  }
  return Promise.resolve();
};

const listModuleParam = reactive({ classify: MODEL_TYPE.LIST, modelName: '', client: 1 });

const menuOptions = [
  { label: '导航菜单', value: 0 },
  { label: '模型菜单', value: 1 },
];

let modelList: any[] = [];

export const resetModelList = () => {
  modelList = [];
};

export const columns: BasicColumn[] = [
  {
    title: '菜单名称',
    dataIndex: 'moduleName',
  },
  {
    title: '菜单类型',
    dataIndex: 'moduleName',
  },

  {
    title: '跳转路径',
    dataIndex: 'path',
  },
  {
    title: '线上活动图标',
    dataIndex: 'openBigMengImg',
    // width: 180,
    customRender: ({ record }) => {
      return h(Image, { width: 60, src: record.openBigMengImg });
    },
  },

  {
    title: '排序',
    dataIndex: 'typeOrder',
    // width: 180,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 120,
  },

  {
    title: '启用状态',
    dataIndex: 'typeStatus',
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      return h(Switch, {
        checked: record.typeStatus === 0,
        loading: record.pendingStatus,
        onChange(checked: boolean) {
          record.pendingStatus = true;
          const newStatus = checked ? 0 : 1;
          const { createMessage } = useMessage();
          try {
            statusSwitchApi({ moduleId: record.moduleId, modelId: newStatus });
            record.typeStatus = newStatus;
            createMessage.success(`已成功修改${menuOptions[record.appMenuType]?.label}状态`);
          } catch {
            createMessage.error(`修改${menuOptions[record.appMenuType]?.label}状态失败`);
          } finally {
            record.pendingStatus = false;
          }
        },
      });
    },
  },
  {
    title: '显示状态',
    dataIndex: 'visible',
    // width: 100,
    customRender: ({ record }) => {
      const visible = record.visible;
      const enable = ~~visible === 1;
      const color = enable ? 'green' : 'red';
      const text = enable ? '显示' : '隐藏';
      return h(Tag, { color: color }, () => text);
    },
  },
];

export const searchFormSchema: FormSchema[] = [
  {
    field: 'moduleName',
    label: '导航名称',
    component: 'Input',
    colProps: { span: 5 },
  },
  {
    field: 'typeStatus',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: [
        { label: '启用', value: '0' },
        { label: '停用', value: '1' },
      ],
    },
    colProps: { span: 8 },
  },
];

export const formSchema = (callback: Fn): FormSchema[] => [
  {
    field: 'moduleName',
    label: '菜单名称',
    required: true,
    component: 'Input',
  },
  {
    field: 'appMenuType',
    label: '菜单类型',
    required: true,
    component: 'Select',
    componentProps: {
      options: menuOptions,
      onChange(val) {
        callback && callback(val);
      },
    },
  },
  {
    field: 'path',
    label: '跳转路径',
    required: true,
    component: 'ApiSelect',
    componentProps() {
      return {
        allowClear: false,
        showSearch: true,
        optionFilterProp: 'label',
        api: async (data) => {
          const ret = await getDictTypeListApi(data);
          ret.forEach((el) => {
            el.label = `${el.label}(${el.value})`;
          });
          return ret;
        },
        labelField: 'label',
        valueField: 'value',
        params: {
          type: DICT.APP_DIC_TYPE,
        },
        getPopupContainer: () => document.body,
      };
    },
  },
  {
    field: 'modelClassify',
    label: '模型类型',
    component: 'ApiSelect',
    componentProps({ formModel }) {
      return {
        allowClear: true,
        api: getDictTypeListApi,
        labelField: 'label',
        valueField: 'intValue',
        params: {
          type: DICT.MODEL_CLASSIFY,
        },
        onChange(v) {
          if (v) {
            if (modelList.length) {
              const obj = modelList.find((i) => i.modelId === formModel.listModelId);
              if (obj) {
                formModel.listModelId = null;
              }
            }
          } else {
            formModel.listModelId = null;
          }

          // if ([MODEL_TYPE.LIST, MODEL_TYPE.COMPLEX].includes(v)) {
          //   formModel.path = modelCompenentName[v];
          // }
          listModuleParam.classify = v;

          // if (formModel.listModelId) {
          //   formModel.listModelId = undefined;
          // }
        },
        getPopupContainer: () => document.body,
      };
    },
  },
  {
    required: true,
    field: 'listModelId',
    label: '模型',
    component: 'ApiSelect',
    ifShow: ({ values }) => values.modelClassify,
    componentProps() {
      return {
        placeholder: '请绑定模型',
        showSearch: true,
        filterOption: false,
        api: async (params) => {
          const data = await getModelAllListApi(params);
          modelList = data;
          return data;
        },
        labelField: 'modelName',
        valueField: 'modelId',
        params: listModuleParam,
        onSearch: useDebounceFn((v) => {
          listModuleParam.modelName = v;
        }, 200),
        getPopupContainer: () => document.body,
      };
    },
  },
  {
    field: 'typeOrder',
    label: '排序',
    component: 'InputNumber',
    required: true,
  },
  {
    field: 'typeStatus',
    label: '启用状态',
    component: 'RadioGroup',
    defaultValue: 0,
    componentProps: {
      options: [
        { label: '启用', value: 0 },
        { label: '禁用', value: 1 },
      ],
    },
  },
  {
    field: 'visible',
    label: '显示状态',
    component: 'RadioGroup',
    defaultValue: 1,
    componentProps: {
      options: [
        { label: '显示', value: 1 },
        { label: '隐藏', value: 0 },
      ],
    },
  },
  {
    field: 'typeEx3Name',
    label: 'APP默认图标路径',
    required: true,
    component: 'Input',
    ifShow: ({ values }) => {
      return values.appMenuType === 0;
    },
  },
  {
    field: 'typeEx4Name',
    label: 'APP活动图标路径',
    required: true,
    component: 'Input',
    ifShow: ({ values }) => {
      return values.appMenuType === 0;
    },
  },
  {
    field: 'bigMengImg',
    label: '线上默认图标',
    component: 'HUpload',
    ifShow: ({ values }) => {
      return values.appMenuType === 0;
    },
    componentProps: {
      title: '图片上传',
    },
  },
  {
    field: 'openBigMengImg',
    label: '线上活动图标',
    ifShow: ({ values }) => {
      return values.appMenuType === 0;
    },
    component: 'HUpload',
    componentProps: {
      title: '图片上传',
      showFileName: false,
    },
  },
  {
    field: 'extMeta',
    label: '路由meta',
    component: 'InputTextArea',
    colProps: { lg: 24 },
    defaultValue: '{}',
    componentProps: {
      rows: 4,
    },
  },
];

export const formSchemaAction: FormSchema[] = [
  {
    field: 'handleName',
    label: '名称',
    component: 'Input',
    required: true,
  },
  {
    field: 'href',
    label: '跳转路径',
    required: true,
    component: 'ApiSelect',
    componentProps() {
      return {
        allowClear: false,
        showSearch: true,
        optionFilterProp: 'label',
        api: async (data) => {
          const ret = await getDictTypeListApi(data);
          ret.forEach((el) => {
            el.label = `${el.label}(${el.value})`;
          });
          return ret;
        },
        labelField: 'label',
        valueField: 'value',
        params: {
          type: DICT.APP_DIC_TYPE,
        },
        getPopupContainer: () => document.body,
      };
    },
  },
  {
    field: 'title',
    label: '类型标题',
    component: 'Input',
  },
  {
    field: 'bgColor',
    label: '背景颜色',
    component: 'Input',
    defaultValue: '',
    // componentProps: {
    //   input: true,
    // },
  },
  {
    field: 'handleOrder',
    label: '排序',
    component: 'InputNumber',
    required: true,
  },
  {
    field: 'handleCode',
    label: '标识',
    required: true,
    component: 'Input',
    rules: [
      {
        validator: checkWord,
        trigger: 'blur',
      },
    ],
  },
  {
    field: 'workflowTemplateId',
    label: '流程模板',
    component: 'ApiSelect',
    componentProps: {
      labelField: 'templatename',
      valueField: 'templateID',
      api: async () => {
        const arr: any[] = [];
        const list = await getTemplateDefinePageApi();
        list.forEach((i) => {
          if (i.list) {
            arr.push(...i.list);
          }
        });
        return arr;
      },
    },
    ifShow: ({ values }) => !values.modelClassify,
  },
  {
    field: 'modelClassify',
    label: '模型类型',
    component: 'ApiSelect',
    componentProps({ formModel }) {
      return {
        allowClear: true,
        api: getDictTypeListApi,
        labelField: 'label',
        valueField: 'intValue',
        params: {
          type: DICT.MODEL_CLASSIFY,
        },
        onChange(v) {
          if (v) {
            if (modelList.length) {
              const obj = modelList.find((i) => i.modelId === formModel.modelId);
              if (obj) {
                formModel.modelId = null;
              }
            }
          }

          listModuleParam.classify = v;
        },
        getPopupContainer: () => document.body,
      };
    },
    ifShow: ({ values }) => !values.workflowTemplateId,
  },
  {
    required: true,
    field: 'modelId',
    label: '模型',
    component: 'ApiSelect',
    ifShow: ({ values }) => values.modelClassify,
    componentProps() {
      return {
        placeholder: '请绑定模型',
        showSearch: true,
        filterOption: false,
        api: async (params) => {
          console.log(params);

          const data = await getModelAllListApi(params);
          modelList = data;
          return data;
        },
        labelField: 'modelName',
        valueField: 'modelId',
        params: listModuleParam,
        onSearch: useDebounceFn((v) => {
          listModuleParam.modelName = v;
        }, 200),
        getPopupContainer: () => document.body,
      };
    },
  },
  {
    field: 'bindImg',
    label: '图标',
    component: 'HUpload',
    componentProps: {
      title: '图标上传',
      showFileName: false,
    },
  },

  {
    field: 'summary',
    label: '描述',
    component: 'InputTextArea',
  },
];

export const actionAuths: BasicColumn[] = [
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '标识',
    width: 120,
    dataIndex: 'handleCode',
  },
  {
    title: '图标',
    width: 120,
    dataIndex: 'bindImg',
    customRender: ({ record }) => h(Image, { width: 20, src: record.bindImg }),
  },
  {
    title: '描述',
    dataIndex: 'summary',
  },
];
